package com.example.demospringsecurity.security.handler;

import com.alibaba.fastjson.JSON;
import com.example.demospringsecurity.domain.ResponseResult;
import com.example.demospringsecurity.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
        log.info(authenticationException.getMessage());
        ResponseResult result = new ResponseResult<>(HttpStatus.UNAUTHORIZED.value(), request.getAttribute("error_msg"));
        String json = JSON.toJSONString(result);
        //处理认证异常
        WebUtils.renderString(response,json);
    }
}
